package com.zunkye.consumer.controller;

import com.zunkye.consumer.service.UserConsumerService;
import com.zunkye.domain.User;
import com.zunkye.resp.ProcessResp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
public class UserController {
    @Autowired
    private UserConsumerService userConsumerService;

    @RequestMapping("/users")
    public String list(Model model){
        List<User> users = userConsumerService.getUsers();
        model.addAttribute("users", users);
        return "user/list";
    }

    @RequestMapping(value = "/users/edit", method = RequestMethod.GET)
    public String edit(@RequestParam(value = "id", required = false) Long id, Model model){
        if(id != null){
            User user = userConsumerService.getUser(id);
            model.addAttribute("user", user);
        }
        return "user/edit";
    }

    @RequestMapping(value = "/users/edit", method = RequestMethod.POST)
    public String add(User user, Model model){
        ProcessResp resp = userConsumerService.addUser(user);
        model.addAttribute("result", resp);
        return "user/result";
    }

    @RequestMapping("/users/remove")
    public String remove(@RequestParam("id") Long id, Model model){
        ProcessResp resp = userConsumerService.removeUser(id);
        model.addAttribute("result", resp);
        return "user/result";
    }
}
